package com.vca.service.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.model.*;
import com.vca.common.constants.SysConfigConstants;
import com.vca.service.service.SystemConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class OssUtils {

    @Autowired
    private SystemConfigService systemConfigService;


    /**
     * 上传文件
     *
     * @param file            上传文件 (MultipartFile)
     * @param fileName        上传文件名
     * @param bucketName      ossBucket名
     * @param folderName      文件夹名
     * @param folderBoolean   是否需要创建文件夹
     * @param callbackBoolean 是否回调
     * @param callbackUrl     回调URL
     * @param callbackBody    回调参数
     */
    public static String uploadFile(MultipartFile file, String fileName, String bucketName, String folderName, boolean folderBoolean, boolean callbackBoolean, String callbackUrl, String callbackBody) {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(SysConfigConstants.REGION, SysConfigConstants.ACCESS_KEY,SysConfigConstants.SECRET_KEY);
        // 上传文件流
        try {
            if (folderBoolean) {
                folderName = folderName + "/";
                ossClient.putObject(bucketName, folderName, new ByteArrayInputStream(new byte[0]));
                ossClient.getObject(bucketName, folderName);
            }
            if (callbackBoolean) {
                System.out.println("callbackBody--" + callbackBody);
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, folderName + fileName, file.getInputStream());
                Callback callback = new Callback();
                callback.setCallbackUrl(callbackUrl);
                callback.setCallbackHost("oss-cn-shanghai.aliyuncs.com");
                callback.setCallbackBody(callbackBody);
                callback.setCalbackBodyType(Callback.CalbackBodyType.JSON);

                putObjectRequest.setCallback(callback);

//                ossClient.putObject(putObjectRequest);

                PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
                // 读取上传回调返回的消息内容

                System.out.println("上传成功：" + putObjectResult.getETag());

                byte[] buffer = new byte[1024];
                putObjectResult.getCallbackResponseBody().read(buffer);
                // 一定要close，否则会造成连接资源泄漏

                System.out.println("--putObjectResult.getETag()-" + putObjectResult.getETag());
                System.out.println("--putObjectResult.getCallbackResponseBody()-" + putObjectResult.getCallbackResponseBody());
                System.out.println("--putObjectResult.getRequestId()-" + putObjectResult.getRequestId());

                putObjectResult.getCallbackResponseBody().close();

                // 关闭client
                ossClient.shutdown();
                return putObjectResult.getETag();
            } else {
                ossClient.putObject(bucketName, folderName + fileName, file.getInputStream());
                // 关闭client
                ossClient.shutdown();
                return "1";
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // 关闭client
            ossClient.shutdown();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // 关闭client
            ossClient.shutdown();
        }
        return "1";
    }

    /**
     * 下载文件
     *
     * @param fileName   下载文件名
     * @param filePath   保存路径
     * @param bucketName ossBucket名
     */
    public static void downloadFile(String fileName, String filePath, String bucketName) {
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(SysConfigConstants.REGION, SysConfigConstants.ACCESS_KEY,SysConfigConstants.SECRET_KEY);
        ossClient.getObject(new GetObjectRequest(bucketName, fileName), new File(filePath));
        ossClient.shutdown();
    }

    /**
     * 根据文件路径删除OSS服务器上的文件
     *
     * @param filePath   文件路径
     * @param bucketName ossBucket名
     */
    public static void deleteFile(String filePath, String bucketName) {
        OSSClient ossClient = new OSSClient(SysConfigConstants.REGION, SysConfigConstants.ACCESS_KEY,SysConfigConstants.SECRET_KEY);
        ossClient.deleteObject(bucketName, filePath);
    }

    /**
     * 创建文件夹
     *
     * @param folderName   文件夹名字
     * @param bucketName ossBucket名
     */
    public static void createFolder(String folderName, String bucketName) {
        OSSClient ossClient = new OSSClient(SysConfigConstants.REGION, SysConfigConstants.ACCESS_KEY,SysConfigConstants.SECRET_KEY);
        ossClient.putObject(bucketName, folderName, new ByteArrayInputStream(new byte[0]));
        ossClient.getObject(bucketName, folderName);
        ossClient.shutdown();
    }

    /**
     * 获取文件有效路径
     *
     * @param fileSrc
     * @return
     */
    public String getOssFileUrl(String fileSrc) {

//        if (ObjectUtil.isNotEmpty(fileSrc)){
//            return fileSrc;
//        }

        String alStorageRegion = systemConfigService.getValueByKey("alStorageRegion");
        String alAccessKey = systemConfigService.getValueByKey("alAccessKey");
        String alSecretKey = systemConfigService.getValueByKey("alSecretKey");
        String alStorageName = systemConfigService.getValueByKey("alStorageName");

        String imgExpirationTime = systemConfigService.getValueByKey("img_expiration_time");
        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setProtocol(Protocol.HTTPS);
        OSSClient ossClient = new OSSClient(alStorageRegion, alAccessKey,alSecretKey,clientConfiguration);
        Date expiration = new Date(new Date().getTime() + Integer.valueOf(imgExpirationTime)*60 * 1000);
        //判断如果是数组 则需要特殊处理
        if(fileSrc.contains("[")){
            String string = JSON.parse(JSONArray.toJSONString(fileSrc)).toString();
            JSONArray array = JSONObject.parseArray(string);
            List<String> list = array.toJavaList(String.class);
            List<String> urlList = new ArrayList<>();
            list.forEach(e->{
                URL url = ossClient.generatePresignedUrl(alStorageName,e, expiration);
                urlList.add(url.toString());
            });
            return JSONObject.toJSONString(urlList);
        }else {
            URL url = ossClient.generatePresignedUrl(alStorageName, fileSrc, expiration);
            return url.toString();
        }
    }

    /**
     * 复制文件
     *
     * @param srcKey
     * @param destKey
     */
    public static void copyFile(String srcKey, String destKey) {

        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(SysConfigConstants.REGION, SysConfigConstants.ACCESS_KEY,SysConfigConstants.SECRET_KEY);
        // 拷贝Object
        CopyObjectResult result = ossClient.copyObject("auditing-video", srcKey, "auditing-video", destKey);

        System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
        // 关闭client
        ossClient.shutdown();
    }


//    public static void main(String[] args) {
//        String ossFileUrl = getOssFileUrl("[\"vcaImage/public/maintain/2021/12/25/63969148b6c4447d918124fd810c1da5m2h9aiylly.jpg\"]");
//        System.out.println(ossFileUrl);
//    }
}
